/**
 * Created by lijizhuang on 16/9/21.
 */
define(['jquery', 'underscore', 'backbone', 'text!modules/roomTypesMgr/modal/updateRoomTypeView.html', 'utils/regutil', 'models/roomTypesMgr/roomType',
    'models/roomTypesMgr/roomModel','models/roomTypesMgr/roomModels', 'models/roomTypesMgr/defaultPrice', 'common'],
    function ($, _, Backbone, UpdateRoomTypeViewTemplate, RegUtil, RoomType, RoomModel, RoomModels, DefaultPrice, Common) {
        var updateRoomTypeView = Backbone.View.extend({
            tagName: 'div',
            id: 'updateRoomType',
            className: 'modal fade',
            template: _.template(UpdateRoomTypeViewTemplate),

            initialize: function () {
                _updateRoomTypeView = this;
            },

            events: {
                'click .addRoom': 'onAddRoomClick',
                'click .removeRoom': 'onRemoveRoomClick',
                'keyup input#initPrice': 'onDefaultPriceEnter',
                'change .weekday-price-item input': 'onWeekdayPriceEnter',
                'click .update-roomtype-footer #saveBtn': 'onSaveClick',
                'focusin input': 'onTextboxFocus'
            },

            onAddRoomClick: function (e) {
                var ele = "<div class=\"roomUnit\"><div style='position: relative'><input type=\"text\" data-roomid=0 class=\"roomInput\" name=\"roomInputTB\"></div><div class='removeRoom'></div></div>";
                $(ele).insertBefore($(e.currentTarget));
                //添加房间,滚动条默认滚到最后
                $(".update-roomtype-body").scrollTop($(".update-roomtype-body").get(0).scrollHeight);
            },

            onRemoveRoomClick: function (e) {
                $(e.currentTarget).parent().remove();
            },

            onDefaultPriceEnter: function (e) {
                var price = $(e.currentTarget).val();
                $('.update-roomtype-body input#mondayPrice').val(price);
                $('.update-roomtype-body input#tuesdayPrice').val(price);
                $('.update-roomtype-body input#wednesdayPrice').val(price);
                $('.update-roomtype-body input#thursdayPrice').val(price);
                $('.update-roomtype-body input#fridayPrice').val(price);
                $('.update-roomtype-body input#saturdayPrice').val(price);
                $('.update-roomtype-body input#sundayPrice').val(price);

                if (!RegUtil.numberReg.test(price)) {
                    _updateRoomTypeView.showError($(e.currentTarget), '输入数字');
                }
                else {
                    _updateRoomTypeView.clearError($(e.currentTarget));
                }

                //手动通知及联修改检测http://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery
                $(".update-roomtype-body .weekday-price-item input[type=text]").trigger("change");
            },

            onWeekdayPriceEnter: function (e) {
                var price = $(e.currentTarget).val();

                if (!RegUtil.numberReg.test(price)) {
                    _updateRoomTypeView.showError($(e.currentTarget), '输入数字');
                }
                else {
                    _updateRoomTypeView.clearError($(e.currentTarget));
                }
            },

            onSaveClick: function () {
                var valid_success = true;

                var $roomTypeName = $('.update-roomtype-body .roomtype-name-item #roomTypeName');
                if ($roomTypeName.val().trim().length === 0) {
                    _updateRoomTypeView.showError($roomTypeName, '房型名称不能为空', 'bottom');
                    valid_success = false;
                }
                else {
                    _updateRoomTypeView.clearError($roomTypeName);
                }

                var $initPrice = $('.update-roomtype-body input#initPrice');
                if (!RegUtil.numberReg.test($initPrice.val())) {
                    _updateRoomTypeView.showError($initPrice, '输入数字', 'top');
                    valid_success = false;
                }
                else {
                    _updateRoomTypeView.clearError($initPrice);
                }

                $('.update-roomtype-body .weekday-price-item input').each(function () {
                    if (!RegUtil.numberReg.test($(this).val())) {
                        _updateRoomTypeView.showError($(this), '输入数字');
                        valid_success = false;
                    }
                    else {
                        _updateRoomTypeView.clearError($(this));
                    }
                });

                $('.update-roomtype-body input.roomInput').each(function () {
                    if ($(this).val().trim().length === 0) {
                        _updateRoomTypeView.showError($(this), '输入房号', 'top');
                        valid_success = false;
                    }
                    else {
                        _updateRoomTypeView.clearError($(this));
                    }
                });

                //验证通过
                if (valid_success) {

                    //post数据到服务端


                    //更新集合
                    var roomTypeId = this.model.get('roomTypeId');
                    var roomTypeName = $('.update-roomtype-body input#roomTypeName').val();
                    var roomTypeNotes = $('.update-roomtype-body input#notes').val();
                    var rank = this.model.get('rank');
                    var roomModels = new RoomModels();

                    $('.update-roomtype-body input.roomInput').each(function () {
                        //如果是之前添加好的房间,可以读取到roomid值不为0
                        var roomId = parseInt($(this).data('roomid'));
                        if(roomId == 0) {
                            //如果是新添加的房间id,这里先mock一下值
                            roomId = Common.getRandomInt(100000, 900000);
                        }

                        var roomModel = new RoomModel();
                        roomModel.set({
                            roomId:roomId, //post数据时,roomId由服务端生成,此处为mock
                            roomNumber:$(this).val(),
                            roomTypeId:roomTypeId, //post数据时,roomTypeId由服务端生成,此处为mock
                            roomTypeName:roomTypeName,
                            bnbId:126323,   //post数据时,bnbId需与真实的关联
                            rank:0 //post数据时,rank由服务端生成,此处为mock
                        });

                        roomModels.add(roomModel);
                    });


                    var initPrice = $('.update-roomtype-body input#initPrice').val();
                    var mondayPrice = $('.update-roomtype-body input#mondayPrice').val();
                    var tuesdayPrice = $('.update-roomtype-body input#tuesdayPrice').val();
                    var wednesdayPrice = $('.update-roomtype-body input#wednesdayPrice').val();
                    var thursdayPrice = $('.update-roomtype-body input#thursdayPrice').val();
                    var fridayPrice = $('.update-roomtype-body input#fridayPrice').val();
                    var saturdayPrice = $('.update-roomtype-body input#saturdayPrice').val();
                    var sundayPrice = $('.update-roomtype-body input#sundayPrice').val();

                    var defaultPrice = new DefaultPrice();
                    defaultPrice.set({
                        roomTypeId: roomTypeId,
                        initPrice: initPrice,
                        mondayPrice: mondayPrice,      //周一至周末每天的价格
                        tuesdayPrice: tuesdayPrice,
                        wednesdayPrice: wednesdayPrice,
                        thursdayPrice: thursdayPrice,
                        fridayPrice: fridayPrice,
                        saturdayPrice: saturdayPrice,
                        sundayPrice: sundayPrice
                    });

                    var roomType = new RoomType();
                    roomType.set({
                        roomTypeId:roomTypeId,
                        roomTypeName:roomTypeName,
                        roomTypeNotes:roomTypeNotes,
                        bnbId:126323,
                        rank:rank,  //post数据时,由服务端计算生成,此处做mock
                        roomModels: roomModels,  //房间集合
                        defaultPrice:defaultPrice //价格信息
                    });

                    this.model.set(roomType.attributes);

                    this.$el.modal('hide');
                }

            },

            onTextboxFocus: function (e) {
                $(e.currentTarget).tooltip('hide');
                _updateRoomTypeView.clearError($(e.currentTarget));
            },

            showError: function (target, wording, place) {
                //var $errMsg = $('#newRoomType .errorMsg');
                //$errMsg.html('*'+wording);
                if (!target.hasClass('validate-failed')) {
                    target.addClass('validate-failed');
                }

                place = (place === undefined || place.length === 0) ? 'top' : place; //默认为top

                target.tooltip({'trigger': 'manual', 'title': wording, 'placement': place});
                target.tooltip('show');
            },

            clearError: function (target) {
                //var $errMsg = $('#newRoomType .errorMsg');
                //$errMsg.html('');

                if (target.hasClass('validate-failed')) {
                    target.removeClass('validate-failed');
                }

                target.tooltip('hide');
            },


            render: function () {
                this.$el.html(this.template(this.model.attributes));

                return this;
            }
        });

        return updateRoomTypeView;
    });